package cn.edu.nju.newsFeed;

import java.util.List;

import cn.edu.nju.R;

import android.app.Activity;
import android.graphics.drawable.BitmapDrawable;
import android.text.Spannable;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public abstract class ItemListAdapter<T extends FeedItem> extends BaseAdapter{
	protected List<T> items; // Derived class must init items
	protected Activity context;
	protected FeedClickableSpan nameSpan;
	protected ForegroundColorSpan contentSpan;
	protected FeedClickableSpan likeSpan;
	
	public ItemListAdapter(Activity activity){
		this.context = activity;
		initTextSpans();
	}
	
	public int getCount(){
		return items.size();
	}
	
	public T getItem(int position){
		return items.get(position);
	}
	
	public long getItemId(int position){
		return position;
	}
	
	protected void initTextSpans(){
		nameSpan = new FeedClickableSpan(context) {			
			@Override
			public void onClick(View widget) {
				// TODO change to the person's homepage
				Toast.makeText(context, ((Integer)widget.getTag(R.id.VIEW_POSITION_TAG)).toString(), Toast.LENGTH_SHORT).show();
			}
		};
		
		contentSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.black));
		
		likeSpan = new FeedClickableSpan(context) {			
			@Override
			public void onClick(View widget) {
				int position = (Integer)widget.getTag(R.id.VIEW_POSITION_TAG);
				T item = getItem(position);
				item.addOneLike();
				setLikeNumberText((TextView)widget, item);
			}
		};
	}
	
	protected void setAvatar(ImageView view, T item){
		if(item.getAvatar() == null){
			view.setBackgroundResource(R.drawable.ic_default_avatar);
		} else{
			view.setBackgroundDrawable(new BitmapDrawable(item.getAvatar()));
		}
	}
	
	protected void setContentText(TextView view, T item){
		String text = item.getPostUserName() + "  " + item.getPostContent();
		view.setText(text);
		Spannable spans = (Spannable)view.getText();
		spans.setSpan(nameSpan, 0, item.getPostUserName().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		spans.setSpan(contentSpan, item.getPostUserName().length() + 1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}
	
	protected void setTimeText(TextView view, T item){
		view.setText(item.getPostTime());
	}
	
	protected void setLikeNumberText(TextView view, T item){
		String text = "" + item.getLikeNumber() + context.getResources().getString(R.string.like);
		view.setText(text);
		Spannable spans = (Spannable)view.getText();
		spans.setSpan(likeSpan, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}
}
